$(function () {
    layui.use('form', function () {
        var form = layui.form;
        // ===== 使用Mock拦截ajax请求
        Mock.mock('/students', function () {
            return Mock.mock({
                'students|5': [{
                    'id|+1': 1,
                    'name|1': '@cname()',
                    'age|16-22': 1,
                    'gender|1': ['男', '女'],
                    'score|30-100': 1,
                }]
            }).students
        })

        let students = JSON.parse(localStorage.getItem('students'));
        if (students) {//检查本地有无数据，有直接取出渲染
            render(students);
        } else {//无，存入，再渲染
            // ===== ajax请求数据
            $.get('/students', function (data) {
                localStorage.setItem('students', JSON.stringify(data));
                render(data)
            }, 'json')
        }

        // ===== 渲染函数
        function render(data) {
            $('tbody').empty();
            data.forEach((item) => {
                if (item.name && item.age && item.gender && item.score) {
                    $('tbody').append(
                        `<tr>
                    <td>${item.id}</td>
                    <td>${item.name}</td>
                    <td>${item.gender}</td>
                    <td>${item.age}</td>
                    <td>${item.score}</td>
                    <td>
                        <button class="layui-btn layui-btn-sm layui-btn-danger" data-id=${item.id}>删除</button>
                        <button class="layui-btn layui-btn-sm layui-btn-warm" data-id=${item.id}>修改</button>
                    
                    </td>
                </tr>`
                    )
                }

            })
        }

        //===== 添加按钮事件
        $('.addBtn').click(function (event) {
            event.preventDefault();
            let addIndex = layer.open({
                type: 1,
                title: ['新增学生', 'font-size:18px;'],
                area: ['500px', '450px'],
                content: `
            <form class="layui-form addForm" action="" style='width:425px;margin-top:30px;'>
                <div class="layui-form-item">
                    <label class="layui-form-label">姓名</label>
                    <div class="layui-input-block">
                        <input type="text" name="name" required lay-verify="required" placeholder="请输入姓名" autocomplete="off"
                            class="layui-input">
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">年龄</label>
                    <div class="layui-input-block">
                        <input type="text" name="age" required lay-verify="required" placeholder="请输入年龄" autocomplete="off"
                            class="layui-input">
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">得分</label>
                    <div class="layui-input-block">
                        <input type="text" name="score" required lay-verify="required" placeholder="请输入得分，分数范围0～100" autocomplete="off"
                            class="layui-input">
                    </div>
                </div>
        
                <div class="layui-form-item">
                    <label class="layui-form-label">单选框</label>
                    <div class="layui-input-block">
                        <input type="radio" name="gender" value="男" title="男">
                        <input type="radio" name="gender" value="女" title="女">
                    </div>
                </div>
                <div class="layui-form-item">
                    <div class="layui-input-block">
                        <button class="layui-btn" lay-submit lay-filter="addSubmit">立即提交</button>
                        <button type="reset" class="layui-btn layui-btn-primary">重置</button>
                    </div>
                </div>
            </form>
            `

            });


            form.render();//需要重新渲染，单选框才会出来
            //表单提交事件
            form.on('submit(addSubmit)', function (data) {
                let newStu = data.field;//获取表单数据
                //从本地取数据
                let students = JSON.parse(localStorage.getItem('students'));
                newStu.id = students.length + 1;//id自增
                students.push(newStu);
                //存回本地
                localStorage.setItem('students', JSON.stringify(students))
                layer.close(addIndex);
                render(students)
                return false; //阻止表单跳转。如果需要表单跳转，去掉这段即可。
            });
        })

        //通过事件委托处理表格的点击事件
        $('tbody').on('click', 'button', function () {
            let id = $(this).attr('data-id') - 0;
            let students = JSON.parse(localStorage.getItem('students'));
            if ($(this).html() === '删除') {
                //在学生数组中找到这个id学生
                students.forEach((item) => {
                    if (item.id === id) {
                        layer.confirm(`是否删除${item.name}?`, { icon: 3, title: '删除学生' }, function (index) {
                            //删除学生信息，保留id
                            delete item.name;
                            delete item.age;
                            delete item.gender;
                            delete item.score;
                            localStorage.setItem('students', JSON.stringify(students))
                            render(students);
                            layer.close(index);
                        });


                    }

                })
            } else {//修改

                students.forEach((item, index) => {
                    if (item.id === id) {
                        console.log(item);
                        let updateIndex = layer.open({
                            type: 1,
                            title: ['修改学生', 'font-size:18px;'],
                            area: ['500px', '450px'],
                            content: `
                        <form class="layui-form addForm" action="" style='width:425px;margin-top:30px;' lay-filter="updateForm">
                            <div class="layui-form-item">
                                <label class="layui-form-label">姓名</label>
                                <div class="layui-input-block">
                                    <input type="text" name="name" required lay-verify="required" placeholder="请输入姓名" autocomplete="off"
                                        class="layui-input">
                                </div>   
                            </div>
                            <div class="layui-form-item">
                                <label class="layui-form-label">年龄</label>
                                <div class="layui-input-block">
                                    <input type="text" name="age" required lay-verify="required" placeholder="请输入年龄" autocomplete="off"
                                        class="layui-input">
                                </div>
                            </div>
                            <div class="layui-form-item">
                                <label class="layui-form-label">得分</label>
                                <div class="layui-input-block">
                                    <input type="text" name="score" required lay-verify="required" placeholder="请输入得分，分数范围0～100" autocomplete="off"
                                        class="layui-input">
                                </div>
                            </div>
                    
                            <div class="layui-form-item">
                                <label class="layui-form-label">单选框</label>
                                <div class="layui-input-block">
                                    <input type="radio" name="gender" value="男" title="男">
                                    <input type="radio" name="gender" value="女" title="女">
                                </div>
                            </div>
                            <div class="layui-form-item">
                                <div class="layui-input-block">
                                    <button class="layui-btn" lay-submit lay-filter="updateSubmit">立即提交</button>
                                    <button type="reset" class="layui-btn layui-btn-primary">重置</button>
                                </div>
                            </div>
                        </form>
                        `
                        });

                        //给表单赋值
                        form.val("updateForm", { //formTest 即 class="layui-form" 所在元素属性 lay-filter="" 对应的值
                            "name": `${item.name}`
                            , "gender": `${item.gender}`
                            , "age": `${item.age}`
                            , "score": `${item.score}`

                        });
                        form.on('submit(updateSubmit)', function (data) {
                            let updateStu = data.field;
                            updateStu.id = item.id;
                            students.splice(index, 1, updateStu);//学生信息重新复制成修改后的值
                            localStorage.setItem('students', JSON.stringify(students))
                            render(students)
                            layer.close(updateIndex);
                            return false;
                        })

                    }

                })
            }

        })
    });
})
